<template>
  <div class="history-container">
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <h2>历史饮食计划</h2>
          <p class="subtitle">查看您之前生成的饮食计划</p>
        </div>
      </template>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <!-- 空状态 -->
      <div v-else-if="mealPlans.length === 0" class="empty-container">
        <el-empty description="暂无历史饮食计划">
          <el-button type="primary" @click="goToGenerate">生成第一个计划</el-button>
        </el-empty>
      </div>

      <!-- 计划列表 -->
      <div v-else class="plans-list">
        <el-card 
          v-for="plan in mealPlans" 
          :key="plan.id"
          class="plan-item"
          shadow="hover"
        >
          <div class="plan-header">
            <div class="plan-info">
              <h3>饮食计划 #{{ plan.id }}</h3>
              <p class="plan-date">创建时间: {{ formatDate(plan.created_at) }}</p>
            </div>
            <div class="plan-actions">
              <el-button 
                type="primary" 
                size="small"
                @click="viewPlanDetail(plan)"
              >
                查看详情
              </el-button>
              <el-button 
                type="success" 
                size="small"
                @click="regeneratePlan(plan)"
              >
                重新生成
              </el-button>
            </div>
          </div>

          <div class="plan-summary">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="summary-stat">
                  <div class="stat-value">{{ plan.total_calories }}</div>
                  <div class="stat-label">每日卡路里</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-stat">
                  <div class="stat-value">{{ getPlanDays(plan) }}</div>
                  <div class="stat-label">计划天数</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-stat">
                  <div class="stat-value">{{ formatDate(plan.start_date) }}</div>
                  <div class="stat-label">开始日期</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-stat">
                  <div class="stat-value">{{ getStrategyName(plan.strategy_used) }}</div>
                  <div class="stat-label">推荐策略</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 计划详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="饮食计划详情"
      width="80%"
      :before-close="closeDetailDialog"
    >
      <div v-if="selectedPlan" class="plan-detail">
        <!-- 计划概览 -->
        <el-card class="detail-overview">
          <template #header>
            <div class="detail-header">
              <h3>计划概览</h3>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="detail-stat">
                <div class="stat-value">{{ selectedPlan.total_calories }}</div>
                <div class="stat-label">每日卡路里</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-stat">
                <div class="stat-value">{{ selectedPlan.daily_meals.length }}</div>
                <div class="stat-label">计划天数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-stat">
                <div class="stat-value">{{ formatDate(selectedPlan.start_date) }}</div>
                <div class="stat-label">开始日期</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-stat">
                <div class="stat-value">{{ formatDate(selectedPlan.end_date) }}</div>
                <div class="stat-label">结束日期</div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 每日饮食详情 -->
        <div class="detail-meals">
          <el-card 
            v-for="(dailyMeal, index) in selectedPlan.daily_meals" 
            :key="index"
            class="detail-meal-card"
          >
            <template #header>
              <div class="meal-header">
                <h4>第 {{ index + 1 }} 天 - {{ formatDate(dailyMeal.date) }}</h4>
                <el-tag type="success">{{ getDayOfWeek(dailyMeal.date) }}</el-tag>
              </div>
            </template>

            <div class="meals-grid">
              <!-- 早餐 -->
              <div class="meal-section">
                <div class="meal-title">
                  <el-icon><Sunny /></el-icon>
                  <span>早餐</span>
                </div>
                <div class="meal-foods">
                  <div 
                    v-for="food in dailyMeal.breakfast" 
                    :key="food.id"
                    class="food-item"
                  >
                    <div class="food-name">{{ food.name }}</div>
                    <div class="food-nutrition">
                      <span class="calories">{{ food.calories }}卡</span>
                      <span class="protein">蛋白质: {{ food.protein }}g</span>
                      <span class="carbs">碳水: {{ food.carbs }}g</span>
                      <span class="fat">脂肪: {{ food.fat }}g</span>
                    </div>
                  </div>
                  <div v-if="dailyMeal.breakfast.length === 0" class="no-food">
                    暂无推荐食物
                  </div>
                </div>
              </div>

              <!-- 午餐 -->
              <div class="meal-section">
                <div class="meal-title">
                  <el-icon><Sunrise /></el-icon>
                  <span>午餐</span>
                </div>
                <div class="meal-foods">
                  <div 
                    v-for="food in dailyMeal.lunch" 
                    :key="food.id"
                    class="food-item"
                  >
                    <div class="food-name">{{ food.name }}</div>
                    <div class="food-nutrition">
                      <span class="calories">{{ food.calories }}卡</span>
                      <span class="protein">蛋白质: {{ food.protein }}g</span>
                      <span class="carbs">碳水: {{ food.carbs }}g</span>
                      <span class="fat">脂肪: {{ food.fat }}g</span>
                    </div>
                  </div>
                  <div v-if="dailyMeal.lunch.length === 0" class="no-food">
                    暂无推荐食物
                  </div>
                </div>
              </div>

              <!-- 晚餐 -->
              <div class="meal-section">
                <div class="meal-title">
                  <el-icon><Moon /></el-icon>
                  <span>晚餐</span>
                </div>
                <div class="meal-foods">
                  <div 
                    v-for="food in dailyMeal.dinner" 
                    :key="food.id"
                    class="food-item"
                  >
                    <div class="food-name">{{ food.name }}</div>
                    <div class="food-nutrition">
                      <span class="calories">{{ food.calories }}卡</span>
                      <span class="protein">蛋白质: {{ food.protein }}g</span>
                      <span class="carbs">碳水: {{ food.carbs }}g</span>
                      <span class="fat">脂肪: {{ food.fat }}g</span>
                    </div>
                  </div>
                  <div v-if="dailyMeal.dinner.length === 0" class="no-food">
                    暂无推荐食物
                  </div>
                </div>
              </div>

              <!-- 零食 -->
              <div class="meal-section">
                <div class="meal-title">
                  <el-icon><Food /></el-icon>
                  <span>零食</span>
                </div>
                <div class="meal-foods">
                  <div 
                    v-for="food in dailyMeal.snacks" 
                    :key="food.id"
                    class="food-item"
                  >
                    <div class="food-name">{{ food.name }}</div>
                    <div class="food-nutrition">
                      <span class="calories">{{ food.calories }}卡</span>
                      <span class="protein">蛋白质: {{ food.protein }}g</span>
                      <span class="carbs">碳水: {{ food.carbs }}g</span>
                      <span class="fat">脂肪: {{ food.fat }}g</span>
                    </div>
                  </div>
                  <div v-if="dailyMeal.snacks.length === 0" class="no-food">
                    暂无推荐食物
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Sunny, Sunrise, Moon, Food } from '@element-plus/icons-vue'
import { dietAPI } from '@/api/index'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const mealPlans = ref([])
const detailDialogVisible = ref(false)
const selectedPlan = ref(null)

// 获取饮食计划列表
const getMealPlans = async () => {
  try {
    loading.value = true
    const response = await dietAPI.getUserMealPlans()
    if (response) {
      mealPlans.value = response
    }
  } catch (error) {
    console.error('获取饮食计划列表失败:', error)
    ElMessage.error('获取计划列表失败')
  } finally {
    loading.value = false
  }
}

// 查看计划详情
const viewPlanDetail = async (plan) => {
  try {
    const response = await dietAPI.getMealPlanDetail(plan.id)
    if (response) {
      selectedPlan.value = response
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取计划详情失败:', error)
    ElMessage.error('获取计划详情失败')
  }
}

// 重新生成计划
const regeneratePlan = async (plan) => {
  try {
    await ElMessageBox.confirm(
      '确定要重新生成这个饮食计划吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 跳转到生成页面，并传递天数参数
    const days = getPlanDays(plan)
    router.push({
      path: '/diet-plan',
      query: { days }
    })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重新生成计划失败:', error)
    }
  }
}

// 关闭详情对话框
const closeDetailDialog = () => {
  detailDialogVisible.value = false
  selectedPlan.value = null
}

// 跳转到生成页面
const goToGenerate = () => {
  router.push('/diet-plan')
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取星期几
const getDayOfWeek = (dateString) => {
  const date = new Date(dateString)
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return days[date.getDay()]
}

// 计算计划天数
const getPlanDays = (plan) => {
  if (plan.daily_meals) {
    return plan.daily_meals.length
  }
  const startDate = new Date(plan.start_date)
  const endDate = new Date(plan.end_date)
  const diffTime = Math.abs(endDate - startDate)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays + 1
}

// 获取策略中文名称
const getStrategyName = (strategy) => {
  const strategyMap = {
    'WeightLossVegetarian': '减脂素食',
    'MuscleGainHighProtein': '增肌高蛋白',
    'BalancedLowCarb': '均衡低碳水',
    'BalancedLowCa': '均衡低碳水' // 处理截断的策略名
  }
  return strategyMap[strategy] || strategy
}

// 组件挂载时获取数据
onMounted(() => {
  getMealPlans()
})
</script>

<style scoped>
.history-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.history-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
}

.subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.loading-container {
  padding: 40px;
}

.empty-container {
  padding: 60px 20px;
  text-align: center;
}

.plans-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.plan-item {
  transition: all 0.3s ease;
}

.plan-item:hover {
  transform: translateY(-2px);
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.plan-info h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 18px;
}

.plan-date {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.plan-actions {
  display: flex;
  gap: 10px;
}

.plan-summary {
  margin-top: 15px;
}

.summary-stat {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

/* 详情对话框样式 */
.plan-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-overview {
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
  color: #333;
}

.detail-stat {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.detail-meals {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-meal-card {
  margin-bottom: 20px;
}

.meal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.meal-header h4 {
  margin: 0;
  color: #333;
}

.meals-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.meal-section {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
}

.meal-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  font-size: 14px;
}

.meal-foods {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.food-item {
  background: white;
  border-radius: 4px;
  padding: 10px;
  border-left: 3px solid #409eff;
}

.food-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 6px;
  font-size: 13px;
}

.food-nutrition {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  font-size: 11px;
}

.calories {
  color: #e6a23c;
  font-weight: bold;
}

.protein {
  color: #67c23a;
}

.carbs {
  color: #409eff;
}

.fat {
  color: #f56c6c;
}

.no-food {
  text-align: center;
  color: #999;
  font-style: italic;
  padding: 15px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-container {
    padding: 10px;
  }
  
  .plan-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .plan-actions {
    width: 100%;
    justify-content: center;
  }
  
  .meals-grid {
    grid-template-columns: 1fr;
  }
}
</style>
